package com.zbw.printlibrary.printSub;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;

import androidx.annotation.NonNull;

import com.printer.sdk.PrinterConstants;
import com.printer.sdk.PrinterInstance;
import com.printer.sdk.usb.USBPort;
import com.zbw.printlibrary.bean.AttributeBean;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.PrinterControlCommon;
import com.zbw.printlibrary.util.CheckUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 方派设备打印
 */
public class PrintFangPai extends PrinterControlCommon {
    private static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";
    private Context mContext;
    private IPrintCallBack mCallBack;
    private UsbDevice mUsbDevice;
    private PrinterInstance mPrinter;

    public PrintFangPai(@NonNull Context mContext, @NonNull IPrintCallBack mCallBack) {
        this.mContext = mContext;
        this.mCallBack = mCallBack;
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_USB_PERMISSION.equals(intent.getAction())) {
                synchronized (this) {
                    mContext.unregisterReceiver(mUsbReceiver);
                    UsbDevice device =  intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                            && mUsbDevice.equals(device)) {
                        mPrinter.openConnection();
                        mCallBack.onConnect("连接成功",true);
                    } else {
                        mCallBack.onConnect("连接失败",false);
                    }
                }
            }
        }
    };

    @Override
    public void connectPrinter() {
        try {
            UsbManager usbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
            if(usbManager == null){
                mCallBack.onConnect("连接失败",false);
                return;
            }
            HashMap<String, UsbDevice> devices = usbManager.getDeviceList();
            List<UsbDevice > deviceList = new ArrayList<>();
            for (UsbDevice device : devices.values()) {
                if (USBPort.isUsbPrinter(device)) {
                    deviceList.add(device);
                }
            }
            if(CheckUtil.isEmpty(deviceList)){
                mCallBack.onConnect("连接失败",false);
                return;
            }
            mUsbDevice = deviceList.get(0);
            mPrinter = PrinterInstance.getPrinterInstance(mContext, mUsbDevice, null);

            if (usbManager.hasPermission(mUsbDevice)) {
                mPrinter.openConnection();
                mCallBack.onConnect("连接成功",true);
            } else {
                // 没有权限询问用户是否授予权限
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0,
                        new Intent(ACTION_USB_PERMISSION), 0);
                IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
                mContext.registerReceiver(mUsbReceiver, filter);
                usbManager.requestPermission(mUsbDevice, pendingIntent); // 该代码执行后，系统弹出一个对话框
            }

        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onConnect("连接失败",false);
        }

    }

    @Override
    public void disConnectPrinter() {
        try {
            mContext.unregisterReceiver(mUsbReceiver);
            mCallBack.onDisConnect("断开连接成功",true);
            mContext = null;
            mCallBack = null;
        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onDisConnect("断开连接失败",false);
        }
    }

    @Override
    public void printTest(List<String> testList) {
        if (CheckUtil.isEmpty(testList)) {
            mCallBack.onPrintResult(false);
            return;
        }
        try {
            mPrinter.initPrinter();
            mPrinter.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_CENTER);
            mPrinter.printText(testList.get(0) + "\n");
            mPrinter.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_LEFT);
            for (int i = 1; i < testList.size(); i++) {
                mPrinter.printText(testList.get(i) + "\n");
            }
            mPrinter.setPrinter(PrinterConstants.Command.PRINT_AND_WAKE_PAPER_BY_LINE, 3);
            mPrinter.cutPaper(66, 50);
            mCallBack.onPrintResult(true);
        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onPrintResult(false);
        }
    }

    @Override
    public void printString(List<AttributeBean> testList) {

    }

    @Override
    public void printStringAndBitmap(List<String> testList, LinkedHashMap<Integer,Bitmap> bitmapHashMap) {
        printTest(testList);
    }

    @Override
    public void blueConnect(String address) {

    }

    @Override
    public void disBlueConnect() {

    }

    @Override
    public void openMoneyBox() {

    }

    @Override
    public boolean isConnected() {
        return mPrinter.openConnection();
    }

    @Override
    public void printString(List<AttributeBean> testList, int width) {

    }

}
